package com.example.administrator.wallet.view.fragment.quotation;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.administrator.wallet.R;
import com.example.administrator.wallet.adapter.TransactionDetailsFragmentAdapter;
import com.example.administrator.wallet.base.BaseFragment;
import com.example.administrator.wallet.constant.Api;
import com.example.administrator.wallet.custom.MessageEvent;
import com.example.administrator.wallet.intf.IRequestCallback;
import com.example.administrator.wallet.intf.IRequestManager;
import com.example.administrator.wallet.model.bean.GetTransactionAssetBean;
import com.example.administrator.wallet.model.bean.WebSocketDepthBean;
import com.example.administrator.wallet.model.bean.WebSocketTransactionsBean;
import com.example.administrator.wallet.utils.RequestFactory;
import com.example.administrator.wallet.utils.SharedPrefsUtil;
import com.example.administrator.wallet.view.activity.find.cointrans.CoinTransactionDetailsActivity;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * A simple {@link Fragment} subclass.
 */
public class BuyTransactionDetailsFragment extends BaseFragment {

    @Bind(R.id.tv_price_buy_1_buy_transaction_fragment)
    TextView tvPriceBuy1;
    @Bind(R.id.tv_price_buy_2_buy_transaction_fragment)
    TextView tvPriceBuy2;
    @Bind(R.id.tv_price_buy_3_buy_transaction_fragment)
    TextView tvPriceBuy3;
    @Bind(R.id.tv_price_buy_4_buy_transaction_fragment)
    TextView tvPriceBuy4;
    @Bind(R.id.tv_price_buy_5_buy_transaction_fragment)
    TextView tvPriceBuy5;
    @Bind(R.id.tv_price_buy_6_buy_transaction_fragment)
    TextView tvPriceBuy6;
    @Bind(R.id.tv_price_buy_7_buy_transaction_fragment)
    TextView tvPriceBuy7;
    @Bind(R.id.tv_price_buy_8_buy_transaction_fragment)
    TextView tvPriceBuy8;
    @Bind(R.id.tv_price_buy_9_buy_transaction_fragment)
    TextView tvPriceBuy9;
    @Bind(R.id.tv_price_buy_10_buy_transaction_fragment)
    TextView tvPriceBuy10;

    @Bind(R.id.tv_price_sell_1_buy_transaction_fragment)
    TextView tvPriceSell1;
    @Bind(R.id.tv_price_sell_2_buy_transaction_fragment)
    TextView tvPriceSell2;
    @Bind(R.id.tv_price_sell_3_buy_transaction_fragment)
    TextView tvPriceSell3;
    @Bind(R.id.tv_price_sell_4_buy_transaction_fragment)
    TextView tvPriceSell4;
    @Bind(R.id.tv_price_sell_5_buy_transaction_fragment)
    TextView tvPriceSell5;
    @Bind(R.id.tv_price_sell_6_buy_transaction_fragment)
    TextView tvPriceSell6;
    @Bind(R.id.tv_price_sell_7_buy_transaction_fragment)
    TextView tvPriceSell7;
    @Bind(R.id.tv_price_sell_8_buy_transaction_fragment)
    TextView tvPriceSell8;
    @Bind(R.id.tv_price_sell_9_buy_transaction_fragment)
    TextView tvPriceSell9;
    @Bind(R.id.tv_price_sell_10_buy_transaction_fragment)
    TextView tvPriceSell10;

    @Bind(R.id.tv_quantity_buy_1_buy_transaction_fragment)
    TextView tvQuantityBuy1;
    @Bind(R.id.tv_quantity_buy_2_buy_transaction_fragment)
    TextView tvQuantityBuy2;
    @Bind(R.id.tv_quantity_buy_3_buy_transaction_fragment)
    TextView tvQuantityBuy3;
    @Bind(R.id.tv_quantity_buy_4_buy_transaction_fragment)
    TextView tvQuantityBuy4;
    @Bind(R.id.tv_quantity_buy_5_buy_transaction_fragment)
    TextView tvQuantityBuy5;
    @Bind(R.id.tv_quantity_buy_6_buy_transaction_fragment)
    TextView tvQuantityBuy6;
    @Bind(R.id.tv_quantity_buy_7_buy_transaction_fragment)
    TextView tvQuantityBuy7;
    @Bind(R.id.tv_quantity_buy_8_buy_transaction_fragment)
    TextView tvQuantityBuy8;
    @Bind(R.id.tv_quantity_buy_9_buy_transaction_fragment)
    TextView tvQuantityBuy9;
    @Bind(R.id.tv_quantity_buy_10_buy_transaction_fragment)
    TextView tvQuantityBuy10;

    @Bind(R.id.tv_quantity_sell_1_buy_transaction_fragment)
    TextView tvQuantitySell1;
    @Bind(R.id.tv_quantity_sell_2_buy_transaction_fragment)
    TextView tvQuantitySell2;
    @Bind(R.id.tv_quantity_sell_3_buy_transaction_fragment)
    TextView tvQuantitySell3;
    @Bind(R.id.tv_quantity_sell_4_buy_transaction_fragment)
    TextView tvQuantitySell4;
    @Bind(R.id.tv_quantity_sell_5_buy_transaction_fragment)
    TextView tvQuantitySell5;
    @Bind(R.id.tv_quantity_sell_6_buy_transaction_fragment)
    TextView tvQuantitySell6;
    @Bind(R.id.tv_quantity_sell_7_buy_transaction_fragment)
    TextView tvQuantitySell7;
    @Bind(R.id.tv_quantity_sell_8_buy_transaction_fragment)
    TextView tvQuantitySell8;
    @Bind(R.id.tv_quantity_sell_9_buy_transaction_fragment)
    TextView tvQuantitySell9;
    @Bind(R.id.tv_quantity_sell_10_buy_transaction_fragment)
    TextView tvQuantitySell10;

    @Bind(R.id.tv_available_fragment_buy_transaction_details)
    TextView tvAvailable;
    @Bind(R.id.listView_latest_transaction_fragment_buy_transaction_details)
    ListView listView;

    @Bind(R.id.et_limit_unit_price_buy_transaction_fragment)
    EditText etLimitUnitPrice;
    @Bind(R.id.iv_price_down_buy_transaction_fragment)
    ImageView ivPriceDown;
    @Bind(R.id.iv_price_up_buy_transaction_fragment)
    ImageView ivPriceUp;
    @Bind(R.id.tv_valuation_buy_transaction_fragment)
    TextView tvValuation;
    @Bind(R.id.et_quantity_buy_transaction_fragment)
    EditText etQuantity;
    @Bind(R.id.iv_quantity_down_buy_transaction_fragment)
    ImageView ivQuantityDown;
    @Bind(R.id.iv_quantity_up_buy_transaction_fragment)
    ImageView ivQuantityUp;
    @Bind(R.id.tv_25_percent_buy_transaction_fragment)
    TextView tv25Percent;
    @Bind(R.id.tv_50_percent_buy_transaction_fragment)
    TextView tv50Percent;
    @Bind(R.id.tv_75_percent_buy_transaction_fragment)
    TextView tv75Percent;
    @Bind(R.id.tv_100_percent_buy_transaction_fragment)
    TextView tv100Percent;
    @Bind(R.id.tv_turnover_buy_transaction_fragment)
    TextView tvTurnover;
    @Bind(R.id.btn_buy_buy_transaction_fragment)
    Button btnBuy;


    private List<TextView> priceBuyList;
    private List<TextView> priceSellList;
    private List<TextView> quantityBuyList;
    private List<TextView> quantitySellList;

    private List<String> priceBuyData;
    private List<String> priceSellData;
    private List<String> quantityBuyData;
    private List<String> quantitySellData;

    private IRequestManager reqequestManager;
    private Gson mGson;
    String token;
    private GetTransactionAssetBean transactionAssetBean;
    private WebSocketDepthBean webSocketDepthBean;
    private CoinTransactionDetailsActivity activity;
    private WebSocketTransactionsBean transactionsBean;
    private int depthId;
    private int transactionsId;
    private TransactionDetailsFragmentAdapter adapter;
    private List<WebSocketTransactionsBean.ResultBean> list;

    @Override
    public void init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        activity = (CoinTransactionDetailsActivity) getActivity();

        initView();

        list = new ArrayList<>();
        adapter = new TransactionDetailsFragmentAdapter(activity,list);
        listView.setAdapter(adapter);

        Bundle bundle = getArguments();
        final String assetType = bundle.getString("toBuyTransactionFragment");
        final String market = bundle.getString("toBuyTransactionFragmentMarket");

        reqequestManager = RequestFactory.getReqequestManager();
        token = SharedPrefsUtil.getValue(getActivity(),"wallet","token","");
        mGson = new Gson();

        reqequestManager.httpPost(Api.BaseUrl + Api.GETTRANSACTIONASSET, Api.getTransactionAsset(token, assetType), new IRequestCallback() {
            @Override
            public void onSuccess(String Response) {
                transactionAssetBean = mGson.fromJson(Response,GetTransactionAssetBean.class);
                int code = transactionAssetBean.getCode();
                if (code == 200){

                    tvAvailable.setText(transactionAssetBean.getData().getList().get(0).getAvailable() + assetType);

                }
            }

            @Override
            public void onFailure(String error) {

            }
        });

        JSONArray jsonArray = new JSONArray();
        jsonArray.add(market);
        jsonArray.add(10);
        jsonArray.add("0");
        depthId = activity.sendMeessage("depth.query",jsonArray);

        JSONArray jsonArray1 = new JSONArray();
        jsonArray1.add(market);
        jsonArray1.add(10);
        jsonArray1.add(0);
        transactionsId = activity.sendMeessage("deals.query",jsonArray1);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MessageEvent messageEvent){
        JSONObject jsonObject = (JSONObject) JSONObject.parse(messageEvent.getMessage());
        if (jsonObject.getInteger("id") == depthId){
            webSocketDepthBean = mGson.fromJson(messageEvent.getMessage(),WebSocketDepthBean.class);
            List<List<String>> asks = webSocketDepthBean.getResult().getAsks();
            List<List<String>> bids = webSocketDepthBean.getResult().getBids();

            etLimitUnitPrice.setText(bids.get(bids.size()-1).get(0));

            depthDataClear();

            for (List<String> ask : asks) {
                priceSellData.add(ask.get(0));
                quantitySellData.add(ask.get(1));
            }
            for (List<String> bid : bids) {
                priceBuyData.add(bid.get(0));
                quantityBuyData.add(bid.get(1));
            }

            setDepthListData();
        } else if (jsonObject.getInteger("id") == transactionsId){
            transactionsBean = mGson.fromJson(messageEvent.getMessage(),WebSocketTransactionsBean.class);
            list.clear();
            list.addAll(transactionsBean.getResult());

            setListViewHeightBaseOnChildren();

            adapter.notifyDataSetChanged();
        }
    }

    private void setDepthListData() {
        for (int i = 0; i < priceBuyData.size(); i++) {
            priceBuyList.get(i).setText(priceBuyData.get(i));
            quantityBuyList.get(i).setText(quantityBuyData.get(i));
        }
        for (int i = 0; i < priceSellData.size(); i++) {
            priceSellList.get(i).setText(priceSellData.get(i));
            quantitySellList.get(i).setText(quantitySellData.get(i));
        }
    }

    private void depthDataClear() {
        priceBuyData.clear();
        priceSellData.clear();
        quantityBuyData.clear();
        quantitySellData.clear();

        for (int i = 0; i < 10; i++) {
            priceBuyList.get(i).setText("");
            priceSellList.get(i).setText("");
            quantityBuyList.get(i).setText("");
            quantitySellList.get(i).setText("");
        }
    }

    private void initView() {
        priceBuyList = new ArrayList<>();
        priceSellList = new ArrayList<>();
        quantityBuyList = new ArrayList<>();
        quantitySellList = new ArrayList<>();

        priceBuyData = new ArrayList<>();
        priceSellData = new ArrayList<>();
        quantityBuyData = new ArrayList<>();
        quantitySellData = new ArrayList<>();

        priceBuyList.add(tvPriceBuy1);
        priceBuyList.add(tvPriceBuy2);
        priceBuyList.add(tvPriceBuy3);
        priceBuyList.add(tvPriceBuy4);
        priceBuyList.add(tvPriceBuy5);
        priceBuyList.add(tvPriceBuy6);
        priceBuyList.add(tvPriceBuy7);
        priceBuyList.add(tvPriceBuy8);
        priceBuyList.add(tvPriceBuy9);
        priceBuyList.add(tvPriceBuy10);

        priceSellList.add(tvPriceSell1);
        priceSellList.add(tvPriceSell2);
        priceSellList.add(tvPriceSell3);
        priceSellList.add(tvPriceSell4);
        priceSellList.add(tvPriceSell5);
        priceSellList.add(tvPriceSell6);
        priceSellList.add(tvPriceSell7);
        priceSellList.add(tvPriceSell8);
        priceSellList.add(tvPriceSell9);
        priceSellList.add(tvPriceSell10);

        quantityBuyList.add(tvQuantityBuy1);
        quantityBuyList.add(tvQuantityBuy2);
        quantityBuyList.add(tvQuantityBuy3);
        quantityBuyList.add(tvQuantityBuy4);
        quantityBuyList.add(tvQuantityBuy5);
        quantityBuyList.add(tvQuantityBuy6);
        quantityBuyList.add(tvQuantityBuy7);
        quantityBuyList.add(tvQuantityBuy8);
        quantityBuyList.add(tvQuantityBuy9);
        quantityBuyList.add(tvQuantityBuy10);

        quantitySellList.add(tvQuantitySell1);
        quantitySellList.add(tvQuantitySell2);
        quantitySellList.add(tvQuantitySell3);
        quantitySellList.add(tvQuantitySell4);
        quantitySellList.add(tvQuantitySell5);
        quantitySellList.add(tvQuantitySell6);
        quantitySellList.add(tvQuantitySell7);
        quantitySellList.add(tvQuantitySell8);
        quantitySellList.add(tvQuantitySell9);
        quantitySellList.add(tvQuantitySell10);
    }

    @Override
    public int getLayoutResource() {
        return R.layout.fragment_buy_transaction_details;
    }

    public void setListViewHeightBaseOnChildren() {
        ListAdapter adapter = listView.getAdapter();
        if (adapter == null){
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < adapter.getCount(); i++) {
            View listItem = adapter.getView(i,null,listView);
            listItem.measure(0,0);// 获取item高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 最后再加上分割线的高度和padding高度，否则显示不完整。
        params.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() -1))
                + listView.getPaddingTop() + listView.getPaddingBottom();
        listView.setLayoutParams(params);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

}
